package com.uitls.utils;

import java.io.FileInputStream;
import java.security.MessageDigest;

public class MD5Util {

    public static String getSHA1(String key) {
        try {
            MessageDigest sha1 = MessageDigest.getInstance("SHA-1");
            sha1.update(key.getBytes());
            return bytesToHexString(sha1.digest());
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String getMD5(String key) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(key.getBytes());
            return bytesToHexString(md5.digest());
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String getFileMd5(String filePath) {
        FileInputStream fis;
        byte[] buffer = new byte[1024];
        int numRead;
        MessageDigest md5;
        try{
            fis = new FileInputStream(filePath);
            md5 = MessageDigest.getInstance("MD5");
            while((numRead = fis.read(buffer)) > 0) {
                md5.update(buffer,0,numRead);
            }
            fis.close();
            return bytesToHexString(md5.digest());
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    private static String bytesToHexString(byte[] bytes) {
        // http://stackoverflow.com/questions/332079
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(0xFF & bytes[i]);
            if (hex.length() == 1) {
                sb.append('0');
            }
            sb.append(hex);
        }
        return sb.toString();
    }
}
